package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class api7MoorCallBack implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(api7MoorCallBack.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        String Syncpram = "";
        String Retupram = "";

        String getMethod = request.getMethod();
        if (getMethod.equals("GET")) {
            Syncpram = request.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }

            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }


        try {

            //业务逻辑部分
            Map<String, String[]> paramMap = request.getParameterMap();
            boolean isCallDetail = paramMap.containsKey("CallType");
            boolean isAgentState = paramMap.containsKey("Exten");
            boolean isSurvey = paramMap.containsKey("SurveyContent");

            if (isCallDetail) {
                Retupram = callDataBack(eliteBean, paramMap);
            } else if (isAgentState) {
                Retupram = AgentStateBack(eliteBean, paramMap);
            } else if (isSurvey) {
                Retupram = SurveyDataBack(eliteBean, paramMap);
            }

        } catch (Exception e) {
            log.error("数据处理错误", e);
            Retupram = "-1"
        }

        return Retupram;
    }

    // 通话状态推送处理
    public static String callDataBack(EliteBean eliteBean, Map<String, String> paramMap) {

        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
            String CallNo = objToString(paramMap.get("CallNo"));
            String CalledNo = objToString(paramMap.get("CalledNo"));
            String CallSheetID = objToString(paramMap.get("CallSheetID"));
            String refCallSheetId = objToString(paramMap.get("refCallSheetId"));
            String CallID = objToString(paramMap.get("CallID"));
            String CallType = objToString(paramMap.get("CallType"));
            String Ring = objToString(paramMap.get("Ring"));
            String RingingDate = objToString(paramMap.get("RingingDate"));
            String Begin = objToString(paramMap.get("Begin"));
            String End = objToString(paramMap.get("End"));
            String QueueTime = objToString(paramMap.get("QueueTime"));
            String Agent = objToString(paramMap.get("Agent"));
            String Exten = objToString(paramMap.get("Exten"));
            String AgentName = objToString(paramMap.get("AgentName"));
            String Queue = objToString(paramMap.get("Queue"));
            String State = objToString(paramMap.get("State"));
            String CallState = objToString(paramMap.get("CallState"));
            String ActionID = objToString(paramMap.get("ActionID"));
            String WebcallActionID = objToString(paramMap.get("WebcallActionID"));
            String RecordFile = objToString(paramMap.get("RecordFile"));
            String FileServer = objToString(paramMap.get("FileServer"));
            String Province = objToString(paramMap.get("Province"));
            String District = objToString(paramMap.get("District"));
            String IVRKEY = objToString(paramMap.get("IVRKEY"));
            String AccountId = objToString(paramMap.get("AccountId"));
            String AccountName = objToString(paramMap.get("AccountName"));
            String CdrVar = objToString(paramMap.get("CdrVar"));
            String DialoutStrVar = objToString(paramMap.get("DialoutStrVar"));
            String HangupPart = objToString(paramMap.get("HangupPart"));

            log.debug("CallSheetID:" + CallSheetID);

            // 处理主数据
            String dealSQL = "select rec_guid from kh_record_expand where CallSheetID = ?";
            List<Map<String, Object>> selectCus = jt.queryForList(dealSQL, CallSheetID);

            log.debug("selectCus：" + selectCus);
            log.debug("检查数据(" + CallSheetID + ") 数量：" + selectCus.size());


            String insertSQLHis = "INSERT INTO kh_record_expand_his (Rec_Guid, CallNo, CalledNo, CallSheetID, refCallSheetId, CallID, CallType, Ring, RingingDate, Begin, End, QueueTime, Agent, Exten, AgentName, Queue, State, CallState, ActionID, WebcallActionID, RecordFile, FileServer, Province, District, IVRKEY, AccountId, AccountName, CdrVar, DialoutStrVar, HangupPart, Sync_Time) VALUES (UUID(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
            int num = jt.update(insertSQLHis, CallNo, CalledNo, CallSheetID, refCallSheetId, CallID, CallType, Ring, RingingDate, Begin, End, QueueTime, Agent, Exten, AgentName, Queue, State, CallState, ActionID, WebcallActionID, RecordFile, FileServer, Province, District, IVRKEY, AccountId, AccountName, CdrVar, DialoutStrVar, HangupPart);

            if (selectCus.size() == 0) {
                String insertSQL = "INSERT INTO kh_record_expand (Rec_Guid, CallNo, CalledNo, CallSheetID, refCallSheetId, CallID, CallType, Ring, RingingDate, Begin, End, QueueTime, Agent, Exten, AgentName, Queue, State, CallState, ActionID, WebcallActionID, RecordFile, FileServer, Province, District, IVRKEY, AccountId, AccountName, CdrVar, DialoutStrVar, HangupPart, Sync_Time) VALUES (UUID(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
                num = jt.update(insertSQL, CallNo, CalledNo, CallSheetID, refCallSheetId, CallID, CallType, Ring, RingingDate, Begin, End, QueueTime, Agent, Exten, AgentName, Queue, State, CallState, ActionID, WebcallActionID, RecordFile, FileServer, Province, District, IVRKEY, AccountId, AccountName, CdrVar, DialoutStrVar, HangupPart);
                log.debug(" 新增数据(" + CallSheetID + ") 数量：" + num);
            } else {

                String updateSQL = '''update kh_record_expand set 
                                                CallNo = ? ,
                                                CalledNo = ? ,
                                                CallSheetID = ? ,
                                                refCallSheetId = ? ,
                                                CallID = ? ,
                                                CallType = ? ,
                                                Ring = ? ,
                                                RingingDate = ? ,
                                                Begin = ? ,
                                                End = ? ,
                                                QueueTime = ? ,
                                                Agent = ? ,
                                                Exten = ? ,
                                                AgentName = ? ,
                                                Queue = ? ,
                                                State = ? ,
                                                CallState = ? ,
                                                ActionID = ? ,
                                                WebcallActionID = ? ,
                                                RecordFile = ? ,
                                                FileServer = ? ,
                                                Province = ? ,
                                                District = ? ,
                                                IVRKEY = ? ,
                                                AccountId = ? ,
                                                AccountName = ? ,
                                                CdrVar = ? ,
                                                DialoutStrVar = ? ,
                                                HangupPart = ? ,
                                                Sync_Time = NOW() where Rec_Guid = ?''';
                num = jt.update(updateSQL, CallNo, CalledNo, CallSheetID, refCallSheetId, CallID, CallType, Ring, RingingDate, Begin, End, QueueTime, Agent, Exten, AgentName, Queue, State, CallState, ActionID, WebcallActionID, RecordFile, FileServer, Province, District, IVRKEY, AccountId, AccountName, CdrVar, DialoutStrVar, HangupPart, selectCus.get(0).get("rec_guid").toString());
                log.debug(" 更新数据(" + CallSheetID + ") 已存在-更新：" + num);
            }

            // 修改录音表录音文件路径
            if (!KHUtil.isNull(RecordFile)) {
                String recordPath = FileServer + "/" + RecordFile;
                Thread.sleep(3000);
                jt.update("update record set documentpath = ? where initcallid = ?", recordPath, CallSheetID);
            }

        } catch (Exception e) {
            log.error("数据处理错误", e);
            return "-1";
        }

        return "200";

    }

    // 坐席状态推送处理
    public static String AgentStateBack(EliteBean eliteBean, Map<String, String> paramMap) {
        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
            String Type = objToString(paramMap.get("Type"));
            String Exten = objToString(paramMap.get("Exten"));
            String ExtenType = objToString(paramMap.get("ExtenType"));
            String ChangeExtenTypeFlag = objToString(paramMap.get("ChangeExtenTypeFlag"));
            String State = objToString(paramMap.get("State"));
            String Agent = objToString(paramMap.get("Agent"));
            String Time = objToString(paramMap.get("Time"));
            String BusyType = objToString(paramMap.get("BusyType"));
            String SendOrder = objToString(paramMap.get("SendOrder"));
            String Timestamp = objToString(paramMap.get("Timestamp"));

            log.debug("Exten:" + Exten + " SendOrder:" + SendOrder);

            // 判断最新调用
            if (SendOrder == "before") {
                log.debug("Exten:" + Exten + " SendOrder:" + SendOrder + " 之前状态放弃处理!");
            } else {

                // 处理主数据
                String dealSQL = "select rec_guid from kh_agent_state where Exten = ?";
                List<Map<String, Object>> selectCus = jt.queryForList(dealSQL, Exten);

                log.debug("selectCus：" + selectCus);
                log.debug("检查数据(" + Exten + ") 数量：" + selectCus.size());

                if (selectCus.size() == 0) {
                    String insertSQL = "INSERT INTO kh_agent_state (Rec_Guid, Type, Exten, ExtenType, ChangeExtenTypeFlag, State, Agent, Time, BusyType, Timestamp, Sync_Time) VALUES (UUID(), ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
                    int num = jt.update(insertSQL, Type, Exten, ExtenType, ChangeExtenTypeFlag, State, Agent, Time, BusyType, Timestamp);
                    log.debug("新增数据(" + Exten + ") 数量：" + num);
                } else {
                    String updateSQL = "UPDATE kh_agent_state SET Type = ?, Exten = ?, ExtenType = ?, ChangeExtenTypeFlag = ?, State = ?, Agent = ?, Time = ?, BusyType = ?, Timestamp = ?, Sync_Time = NOW() WHERE Rec_Guid = ?";
                    int num = jt.update(updateSQL, Type, Exten, ExtenType, ChangeExtenTypeFlag, State, Agent, Time, BusyType, Timestamp, selectCus.get(0).get("rec_guid").toString());
                    log.debug("更新数据(" + Exten + ") 数量：" + num);
                }
            }
        } catch (Exception e) {
            log.error("数据处理错误", e);
            return "-1";
        }

        return "200";

    }

    // 满意度结果推送处理
    public static String SurveyDataBack(EliteBean eliteBean, Map<String, String> paramMap) {

        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
            String CallSheetID = objToString(paramMap.get("CallSheetID"));
            String SurveyContent = objToString(paramMap.get("SurveyContent"));

            log.debug("CallSheetID:" + CallSheetID);

            // 处理主数据
            String dealSQL = "select rec_guid from kh_satisfaction_survey where CallSheetID = ?";
            List<Map<String, Object>> selectCus = jt.queryForList(dealSQL, CallSheetID);

            log.debug("selectCus：" + selectCus);
            log.debug("检查数据(" + CallSheetID + ") 数量：" + selectCus.size());

            if (selectCus.size() == 0) {
                String insertSQL = "INSERT INTO kh_satisfaction_survey (Rec_Guid, CallSheetID, SurveyContent, Sync_Time) VALUES (UUID(), ?, ?, NOW())";
                int num = jt.update(insertSQL, CallSheetID, SurveyContent);
                log.debug(" 新增数据(" + CallSheetID + ") 数量：" + num);
            } else {
                log.debug(" 忽略数据(" + CallSheetID + ") 已存在-忽略");
            }
        } catch (Exception e) {
            log.error("数据处理错误", e);
            return "-1";
        }

        return "200";

    }

    public static String objToString(String[] obj) {

        if (obj == null) {
            return "";
        } else {
            return StringUtils.join(obj, "-");
        }
    }

}